package sdk.webview.fmc.com.fmcsdk.util;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;





public class AESUtil {


    // static String data = "123456RWEQR";
    static String key = "abcdef0123456789"; // 16位
    static String iv = "0123456789abcdef"; // 16位

    /**
     * 加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptAESExpand(String data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding"); // 参数分别代表 算法名称/加密模式/数据填充方式
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("utf-8"));

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

           // String encode = Base64.getEncoder().encodeToString(encrypted);

            String encode =encodeBase64(encrypted);


            //如果数据过长base64会自动添加换行符
            encode = encode.replaceAll(System.lineSeparator(), "");

            return getChar(9) + encode;

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 随机固定数目字符串
     *
     * @param length
     * @return
     */
    public static String getChar(int length) {
        char[] ss = new char[length];
        int i = 0;
        while (i < length) {
            int f = (int) (Math.random() * 3);
            if (f == 0) {
                ss[i] = (char) ('A' + Math.random() * 26);
            } else if (f == 1) {
                ss[i] = (char) ('a' + Math.random() * 26);
            } else {
                ss[i] = (char) ('0' + Math.random() * 10);
            }
            i++;
        }
        String str = new String(ss);
        return str;
    }

    /**
     * 解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptAESExpand(String data) {
        String ordata = data;
        try {
            data = data.substring(9);
//            Decoder decoder = Base64.getDecoder();
//            byte[] buffer = decoder.decode(data);

            byte[] buffer =   decodeBase64(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("utf-8"));

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(buffer);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception e) {
            return ordata;
        }
    }

    public static void main(String[] args) {
        long ts = 1536746038877L;
        String src = "test";

        String ciphertext = AESUtil.encryptAESExpand(src);
        System.out.println("加密后：" + ciphertext);

        String txt = AESUtil.decryptAESExpand(ciphertext);
        System.out.println("解密后：" + txt);

    }


    private static String encodeBase64(byte[] input) {
        byte[] encodedBytes = Base64.encode(input, Base64.DEFAULT);
        return new String(encodedBytes);
    }

    private static byte[] decodeBase64(String encodedString) {
        byte[] decodedBytes = Base64.decode(encodedString, Base64.DEFAULT);
        return decodedBytes;
    }

}

